package cn._51doit.flink.day02;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.connector.jdbc.JdbcConnectionOptions;
import org.apache.flink.connector.jdbc.JdbcExecutionOptions;
import org.apache.flink.connector.jdbc.JdbcSink;
import org.apache.flink.connector.jdbc.JdbcStatementBuilder;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JDBCSink1 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //1,tom,18
        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<Tuple3<Integer, String, Integer>> tpStream = lines.map(new MapFunction<String, Tuple3<Integer, String, Integer>>() {

            @Override
            public Tuple3<Integer, String, Integer> map(String line) throws Exception {
                String[] fields = line.split(",");
                int id = Integer.parseInt(fields[0]);
                String name = fields[1];
                int age = Integer.parseInt(fields[2]);
                return Tuple3.of(id, name, age);
            }
        });

        //将数据写入到MySQL中
        tpStream.addSink(
                JdbcSink.sink(
                        "insert into tb_users (id, name, age) values (?, ?, ?)",
                        new JdbcStatementBuilder<Tuple3<Integer, String, Integer>>() {
                            @Override
                            public void accept(PreparedStatement preparedStatement, Tuple3<Integer, String, Integer> tp) throws SQLException {
                                preparedStatement.setInt(1, tp.f0);
                                preparedStatement.setString(2, tp.f1);
                                preparedStatement.setInt(3, tp.f2);
                            }
                        },
                        JdbcExecutionOptions.builder()
                                .withBatchSize(10) //批量写入的条数
                                .withBatchIntervalMs(30000) //批量写入的时间
                                .withMaxRetries(5) //写入失败重试次数
                                .build(),
                        new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
                                .withUrl("jdbc:mysql://node-3.51doit.cn:3306/bigdata?characterEncoding=utf-8")
                                .withDriverName("com.mysql.jdbc.Driver")
                                .withUsername("root")
                                .withPassword("123456")
                                .build()
                )
        );

        env.execute();


    }

}
